<?php
namespace API\Model;

use Think\Model;
use Think\Page;
use Common\Tool\Tool;
use Common\TraitClass\callBackClass;

/**
 * 商品模型 
 */
class GoodsModel extends Model
{
    use callBackClass;
    private static $obj ;
    
    private $goods = NULL;
    /**
     * 筛选数据
     */
    public function screenData(array $array)
    {
        if (empty($array) || !is_array($array))
        {
            return array();
        }
        $offset = ($array['page'] - 1) * $array['page_size'];
        $result = $this
          ->field('id,pic_url,title,price_new')
          ->where( 'title LIKE "%'.$array['title'].'%" AND type=1 AND shangjia=1')
          ->order('sort_num ASC')
          ->page($offset.','.$array['page_size'])
          ->select();
        
        return $result;
    }
    
    /**
     * 商品详情 
     */
    public function find($options =array(), Model $model)
    {
        if (!is_object($model) || !($model instanceof Model) )
        {
            return array();
        }
        $data = parent::find($options);

        if (!empty($data)) 
        {
            //反序列化图片
            $data['pic_tuji'] = !empty($data['pic_tuji']) ? unserialize($data['pic_tuji']) : null;
            if ($data['pic_tuji']) {
                $path = C('IMG_ROOT_PATH');
                foreach ($data['pic_tuji'] as $key => &$value)
                {
                    if ( false === strpos($value, $path)) {
                        $value = $path.$value;
                    }
                }
            }
            //发序列化套餐
            $data['taocan']   = !empty($data['taocan']) ? unserialize($data['taocan'])   : null;
//             $array['id'] = intval($array['id']);
//             //限购代码
//             $result_orders_record = $model->field('id')->where('user_id = "'.$_SESSION['user_id'].'" and goods_id = "'.$options['where']['id'].'"')->find();
            
//             if(!empty($result_orders_record)){
//               $data['xiangou_yigoumai'] = 1;	//限购已购买
//             }
            //限时购判断
//             $data['xianshi'] = isset($data['xianshi_status']) ? 'yes' : 'no';
            
//             $xianshi=$this->where('id = "'.$options['where']['id'].'" and xianshi_status = 1')->getField('xianshi_start,xianshi_over');
//             if (!empty($xianshi))
//             {
//                 $new[0]=array_keys($xianshi);
    
//                 $new[1]=array_values($xianshi);
//                 $start=$new[0][0];
//                 $over=$new[1][0];
//                 //限时购的时间判断
//                 $time=date("Y-m-d H:i:s");
//                 //echo $start;
//                 if($time<$start){
//                     $cha=strtotime($start)-strtotime($time);
//                     $goodsDetail['cha'] = $cha;//即将开始
//                     $goodsDetail['xianshi_time'] = 0;//即将开始
//                 }else if($time>$over){
//                     $goodsDetail['xianshi_time'] = 2;//活动截至
//                 }else{
//                     $goodsDetail['xianshi_time'] = 1;
//                 }
//             }
        }
        return $data;
    }
    /**
     * 查询要购买的商品
     */
    public function getGoods(array $options, array $goodsNumber, $type=0)
    {
        if (!is_array($options) || empty($options) || empty($goodsNumber) || !is_array($goodsNumber)) {
            return array();
        }
        $data = parent::select($options);
        $sumMonery = 0;
        if (!empty($data))
        {
            foreach ($goodsNumber as $goodsId => $goodsNum)
            {
                foreach ($data as $primayKey => &$goods)
                {
                    if ($goodsId === intval($goods['id']))
                    {                
                        $goods['goods_num']    = $goodsNum;
                        $goods['total_monery'] = $goods['price_new'] * $goodsNum;
                        $goods['type']         = $type;
                        $sumMonery += $goods['total_monery'];
                    }
                }
            }
        }
        return array('goods_info' => $data, 'total_monery' => $sumMonery);
    }
    
    /**
     * 计算运费
     * @param $goods 商品id和数量的组合(二维数组)
     * @param $area  省份名字
     * $goods,$area
     * 数组示例: 
     * $goods=array(
     *      0=>array('id'=>1,'num'=>2),
     *      1=>array('id'=>1,'num'=>3)
     * );
     * 省份名字示例: $area='河北省';
     */
    public function countFreight($goods, $area ,  $data)
    {
        if (empty($goods) || !is_array($goods) || empty($area) || !is_string($area)) 
        {
            return false;
        }
        //获取包邮城市
        $baoyou_area = C('free');

        
        $yunfei = 0;

        $pattern = '/^\d+g$/';
        $patterns = '/^\d+g\*\d$/';
        $row = null;
        $zhongliang = 0;

        foreach ($goods as $goodsrow) 
        {
            $row = parent::find(array(
                'where' => array('id' => $goodsrow['id']),
                'field' => array('zhongliang')
            ));
            preg_match($pattern, $row['zhongliang'], $matches);
            preg_match($patterns, $row['zhongliang'], $matche);
    
            if (!empty($matches) || !empty($matche)) {
    
                $row['zhongliang'] = str_replace('g', '', $row['zhongliang']);
                $a = explode('*', $row['zhongliang']);
                $rst = 1;
                
                foreach ($a as $k) {
                    $rst *= $k;
                }
                if (($row['min_yunfei'] != 0) || ($row['is_baoyou'] == 0)) {//如果其他地方不包邮或者江浙沪皖不包邮,则算出重量，方便计费
                    $zhongliang += $rst * $goodsrow['goods_num'];
                }
                if($row['is_baoyou'] == 1){//即使上面有运费，如果江浙沪皖包邮，则直接将重量设置为0，下面计算运费就直接返回0
                    if(in_array($area,$baoyou_area)){
                        $zhongliang=0;
                    }
                }
            }
            	
            if($zhongliang==0){
                $yunfei+= 0;
            }else{
                if (!empty($data['ykg']) && $data['ykg'] == 3) {
                    if ($zhongliang <= 3000) {
                        $yunfei+= $data['money'];
                    } else {
                        $zhongliang = $zhongliang - 3000;//超出的部分
                        $times = ceil($zhongliang/1000);//算出整数的公斤数
                        $yunfei+= ($data['money']+$data['onemoney']*$times);
                    }
                } else {
                    if ($zhongliang <= 1000 && !empty($data)) {
                        $yunfei+= $data['money'];
                    } else {
                        $zhongliang = $zhongliang - 1000;//超出的部分
                        $times = ceil($zhongliang/1000);//算出整数的公斤数
                        $yunfei+= ($data['money']+$data['onemoney']*$times);
                    }
                }
            }
        }
        return $yunfei;
    }
    
    /**
     * 获取关键词商品数据 
     */
     public function getGoodsData(array $data, $checkKey = 'goods_class_id')
     {
         if (empty($data[$checkKey]))
         {
             return array();
         }
         $totalRows = $this->where(array('class_id' => array('in', $data[$checkKey]), 'shangjia' => 1, 'type' => 1, 'title' => array('like', $data['hot_words'])))->count();
          
         $page = new Page($totalRows, PAGE_SIZE);
         $goods = parent::select(array(
             'where' => array('class_id' => array('in', $data[$checkKey]), 'shangjia' => 1, 'type' => 1,'title' => array('like', $data['hot_words'])),
             'field' => array('id', 'pic_url', 'price_new', 'price_old', 'fanli_jifen', 'title', 'type'),
             'limit' => $page->firstRow. ','. $page->listRows
         ));
         return array('data' => $goods, 'page' => $page->show());
     }
     
     /**
      * 根据分类编号查询子类商品
      * @return array
      */
     public function getGoodsForClassId(array $options)
     {
         if (empty($options))
         {
             return array();
         }
         return parent::select($options);
     }
     
     public function getGoodsById(array $options, $default = 'find')
     {
         if (empty($options))
         {
             return $options;
         }
         return parent::$default($options);
     }
     
     protected function _before_update( &$data, $options)
     {
         $data['update_time'] = time();
         return $data;
     }
     
     protected function _before_insert(&$data, $options)
     {
         $data['update_time'] = time();
         $data['create_time'] = time();
         return $data;
     }
     /**
      * 库存是否可减
      */
     public function isReduce(array $goodIds)
     {
       
         if (empty($goodIds))
         {
             return false;
         }
         
         $goods = Tool::characterJoin($goodIds);
         $this->goods = $this->field('id, kucun')->where('id in('.$goods.')')->select();
        
         //排序
         usort( $this->goods, array($this, 'compare'));
       
         if (empty($this->goods))
         {
             return false;
         }
         
         foreach ( $this->goods as $key => &$value)
         {
             if ($value['kucun'] - $goodIds[$key]['goods_num'] < 0 && $value['id'] == $goodIds[$key]['goods_id'])
             {
                 return false;
             }
         }
         
         return true;
     }
     //减少库存
     public function reduceAmount(array $goodIds)
     {
         if (empty($goodIds))
         {
             return false;
         }
         $status = false;
         
        
         foreach ($this->goods as $key => &$value)
         {
             if ($value['kucun'] - $goodIds[$key]['goods_num'] > 0 && $value['id'] == $goodIds[$key]['goods_id'])
             {  
                 //延迟更新
                 $status = $this->where('id = "'.$value['id'].'"')->setDec('kucun', $goodIds[$key]['goods_num'], 10);
             }
         }
         return $status;
     }
     
     /**
      * 从订单中查询商品信息 
      */
     public function getGoodsNameById(array $data, $filed = 'title,id as goods_id', array $buildKey = array('title'))
     {
         if (empty($data))
         {
             return $data;
         }
         $goods = Tool::characterJoin($data);
         
        
       
         if (empty($goods))
         {
             return $goods;
         }
         $goods = $this->field($filed)->where('id in('.$goods.')')->select();
        
        
         //排序
         usort( $goods, array($this, 'compare'));
        
         $data  = Tool::parseTwoArray($data, $goods, 'goods_id',$buildKey);
         
         return $data;
     }
     
     /**
      * 根据订单子表的数据查询商品数据
      * @return array
      */
     public function getGoodsByChildrenOrderData(array $data)
     {
         if (empty($data))
         {
             return array();
         }
         usort($data, array($this, 'compare'));
         //用户【考虑到用户连续购买同一件商品】【后续优化】
         foreach ($data as $key => &$value)
         {
             $value['goods'] = parent::select(array(
                 'field' => 'pic_url,price_old,id as goods_id,title, price_new as goods_price',
                 'where' => array('id' => array('in', $value['goods_id'])),
                 'order' => 'goods_id DESC',
             ));
         }
         usort($data, array($this, 'compareOrder'));
         
         //处理商品数量
         foreach ($data as $key => &$value)
         {
             if (false !== strpos($value['goods_num'], ','))
             {
                 Tool::addString($value['goods_num']);
                 $goodsNum = Tool::joinString($value['goods_num']);
                 
                 $value['goods_num'] = $goodsNum;
             }
         }
         //移植商品数量到具体商品
         foreach ($data as $key => &$value)
         {
             if (!empty($value['goods']))
             {
                 foreach ($value['goods'] as $goods => &$name)
                 {
                     if (is_array($value['goods_num']) && array_key_exists($name['goods_id'], $value['goods_num']))
                     {
                         $value['goods'][$goods]['goods_num'] = $value['goods_num'][$name['goods_id']];
                     }
                     else if ($name['goods_id'] === $value['goods_id']) 
                     {
                         $value['goods'][$goods]['goods_num'] = $value['goods_num'];
                     }
                 }
             }
         }
         return $data;
     }
     
     public static function getInitation()
     {
         $class = __CLASS__;
         return self::$obj = !(self::$obj instanceof $class) ? new self() : self::$obj;
     }
     
     /**
      * 判断该商品是否存在 
      */
     public function isHaveGoods($id)
     {
         if (empty($id) || !is_numeric($id))
         {
             return array();
         }
         $pk = $this->getPk();
         return $this->where($pk.' = "%s"', $id)->getField($pk);
     }
     
     /**
      * 更新库存
      */
     public function updateStock(array $goods)
     {
         if (empty($goods) )
         {
             return array();
         }
         $status = false;
         foreach ($goods as $key => $value)
         {
             $status = $this->where('id = "%s"', $value['goods_id'])->setInc('kuncun', $value['goods_num'], 7);
         }
         
         return $status;
     }
}